import OSS from "ali-oss";
import { aliAccessKeyId, aliAccessKeySecret, aliOssBucket, aliRegion } from "@/configs/ali";
import path from "path";
import { renameSync, rmSync } from "fs";
import { v4 } from "uuid";

const client = new OSS({
	region: aliRegion,
	accessKeyId: aliAccessKeyId,
	accessKeySecret: aliAccessKeySecret,
	bucket: aliOssBucket,
});
export const uploadAliOss = (file: Express.Multer.File) => {
	return new Promise(async (resolve, reject) => {
		const fileBase = v4() + path.extname(file.originalname);
		const localFilePath = path.dirname(file.path) + "/" + fileBase;
		const remoteFilePath = "/shuang-yuan-zhi/upload/" + fileBase;
		renameSync(file.path, localFilePath);
		try {
			const { res } = await client.put(remoteFilePath, localFilePath);
			if (res.status !== 200) throw new Error(res.rt.toString());
			resolve(remoteFilePath);
		} catch (error) {
			reject(error);
		} finally {
			rmSync(localFilePath);
		}
	});
};
export const downloadAliOss = async (fileName: string) => {
	return await client.get(fileName);
};
